<template>
  <div class="phone-form">
    <a-alert class="alert-err" v-show="isLoginError" type="error" showIcon message="手机快捷登录失败，请稍后重试" />
    <a-form
      :form="form"
      class="login-form"
      @submit="handleSubmit"
    >
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="[
            'phone',
            { rules: [{ required: true, message: '请输入手机号码!', whitespace: true, trigger: 'change' }] },
          ]"
          placeholder="手机号"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="mobile" style="color: rgba(0,0,0,.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="[
            'identify',
            { rules: [{ required: true, message: '', whitespace: true, trigger: 'change' }, { validator: validateSmsCode }] },
          ]"
          placeholder="短信验证码"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="mail" style="color: rgba(0,0,0,.25)" />
          <span slot="suffix">
            <a-button type="link" :class="{ 'not-click': state.smsSendBtn }" size="small" @click.stop.prevent="handleSendCode">{{ state.codeText }}</a-button>
          </span>
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-button
          type="primary"
          size="large"
          html-type="submit"
          class="login-form-sign"
          :loading="state.loginBtn"
          :disabled="state.loginBtn"
        >
          登录
        </a-button>
      </a-form-item>
    </a-form>
    <puzzle-verification
      width="400"
      height="240"
      blockSize="60"
      v-model="isShow"
      :onSuccess="handleSuccess"
    ></puzzle-verification>
  </div>
</template>

<script>
// import { timeFix } from '@/utils/util'
import { mapActions } from 'vuex'
import PuzzleVerification from '@/components/puzzle-verification'
import { sendSmsCode, querySmsCode } from '@/api/common'
import debounce from 'lodash.debounce'
export default {
  components: {
    PuzzleVerification
  },
  data () {
    return {
      isShow: false,
      loginBtn: false,
      isSuccess: false,
      isLoginError: false,
      state: {
        time: 60,
        loginBtn: false,
        smsSendBtn: false,
        codeText: '获取验证码'
      },
      form: this.$form.createForm(this, { name: 'phoneForm' })
    }
  },
  methods: {
    ...mapActions(['Login']),
    handleSuccess () {
      const { state, form } = this
      this.isShow = false
      this.isSuccess = false
      state.smsSendBtn = true
      const interval = window.setInterval(() => {
        if (state.time-- <= 0) {
          state.time = 60
          state.smsSendBtn = false
          state.codeText = '获取验证码'
          window.clearInterval(interval)
        } else {
          state.codeText = `${state.time}秒后重新发送`
        }
      }, 1000)

      const hide = this.$message.loading('短信验证码正在发送中...', 0)
      sendSmsCode({ Phone: form.getFieldValue('phone') }).then(res => {
        if (res.code === 200) {
          this.$notification['success']({
            message: '提示',
            description: '短信验证码发送成功，可能会有延后请耐心等待',
            duration: 8
          })
          this.isSuccess = true
        } else {
          this.$notification['error']({
            message: '提示',
            description: '当前登录手机号不存在,请检查后重新输入',
            duration: 8
          })
          clearInterval(interval)
          state.time = 60
          state.smsSendBtn = false
        }
        setTimeout(hide, 100)
        this.isShow = false
      }).catch(err => {
        setTimeout(hide, 1)
        clearInterval(interval)
        state.time = 60
        state.smsSendBtn = false
        this.isShow = false
        this.isSuccess = false
        this.requestFailed(err)
      })
    },
    handleSendCode (e) {
      e.preventDefault()
      const { form: { validateFields } } = this

      validateFields(['phone'], { force: true }, (err, values) => {
        if (!err) {
          this.isShow = true
        }
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        Login,
        state
      } = this
      this.form.validateFields((err, values) => {
        if (!err) {
          state.loginBtn = true
          const loginParams = { ...values }
          delete loginParams.phone
          delete loginParams.identify
          loginParams.username = values.phone
          loginParams.password = values.identify
          loginParams.grant_type = 'password'
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
          this.loginSuccess()
        }
      })
    },
    loginSuccess (res) {
      this.$router.push({ path: '/' })
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
      this.$notification['error']({
      message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    },
    querySmsCode: debounce(function (obj) {
      return new Promise((resolve, reject) => {
        querySmsCode(obj).then(res => {
          resolve(res)
        }).catch((err) => {
          reject(err)
        })
      })
    }, 500, { leading: true, trailing: true }),
    validateSmsCode (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入短信验证码!'))
      } else {
        const { form: { getFieldValue }, isSuccess } = this
        const _phone = getFieldValue('phone')
        if (isSuccess && value.length === 6) {
          this.querySmsCode({
            Phone: _phone,
            YZM: value
          }).then(res => {
            if (res.code === 200) {
              callback()
            } else {
              callback(new Error('验证码输入有误'))
            }
          }).catch(() => {
            callback()
          })
        } else {
          callback()
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .phone-form {
    .alert-err {
      margin-bottom: 24px;
    }
    .ant-form-item:nth-child(2) {
      margin-bottom: 0;
    }
    .login-form-sign {
      width: 100%;
      margin-top: 20px;
    }
    .not-click {
      color: #B3B9C7;
      pointer-events: none;
    }
    .code-tips {
      font-size: 12px;
    }
  }
</style>
